using System;
using System.Net;

namespace NetDns
{
	/// <summary>
	/// An Srv (Service) Resource Record (RR)
	/// </summary>
	[Serializable]
	public class Srv : IRecord, IComparable
	{
		// an MX record is a domain name and an integer preference
		private readonly string		hostname;
		private readonly int		priority;
		private readonly int		weight;
		private readonly int		port;

		// expose these fields public read/only
		public string Hostname	{ get { return hostname; }}
		public int Priority		{ get { return priority; }}
		public int Weight { get { return weight; } }
		public int Port { get { return port; } }

				
		/// <summary>
		/// Constructs an MX record by reading bytes from a return message
		/// </summary>
		/// <param name="pointer">A logical pointer to the bytes holding the record</param>
		internal Srv(Pointer pointer)
		{
			priority = pointer.ReadShort();
			weight = pointer.ReadShort();
			port = pointer.ReadShort();
			hostname = pointer.ReadDomain();
		}

		public override string ToString()
		{
			return string.Format("Priority: {0}, Weight: {1}, Port: {2}, Host: {3}", priority.ToString(), weight.ToString(), port.ToString(), hostname);
		}

		public int CompareTo(object obj)
		{
			Srv s = (Srv) obj;

			//first, try to order based on priority
			if (s.priority < this.priority) return 1;
			if (s.priority > this.priority) return -1;

			//If two objects have the same priority, compare weight
			if (s.weight < this.weight) return 1;
			if (s.weight > this.weight) return -1;

			//As a last resort we order on hostname.
			return -s.hostname.CompareTo(this.hostname);

		}
	}
}
